package mume.infoRetriever;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class AsinInfoHandler extends DefaultHandler{
	private String artist = "";
	private String artistId = "";
	private String album = "";
	private String albumId = "";
	
	private boolean artistOpen;
	private boolean albumOpen;
	private boolean albumTitleOpen;
	private boolean artistNameOpen;
	
	public AsinInfoHandler (){
		super();
    }
	
	public String getArtist() {
		return artist;
	}
	public String getArtistId() {
		return artistId;
	}
	public String getAlbum() {
		return album;
	}
	public String getAlbumId() {
		return albumId;
	}
	
	public String toString() {
		return "artist: " + artist + " id: " + artistId + " album: " + album + " id: " + albumId;
	}
	public void startDocument() throws SAXException {
		artistOpen = false;
		albumOpen = false;
		albumTitleOpen = false;
		artistNameOpen = false;
	}
	public void startElement(String uri, String localName, String qName,
			Attributes atts) throws SAXException {
		if(localName.equals("artist")) {
			artistOpen = true;
			artistId = atts.getValue("id");
		} else if(localName.equals("release")) {
			albumOpen = true;
			albumId = atts.getValue("id");
		}else if(albumOpen && localName.equals("title")) {
			albumTitleOpen = true;
		}else if(artistOpen && localName.equals("name")) {
			artistNameOpen = true;
		}
		
	}
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if(localName.equals("artist")) {
			artistOpen = false;
		} else if(localName.equals("release")) {
			albumOpen = false;
		} else if(albumOpen && localName.equals("title")) {
			albumTitleOpen = false;
		} else if(artistOpen && localName.equals("name")) {
			artistNameOpen = false;
		}
	}
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		if(artistNameOpen || albumTitleOpen){
			String help = "";
			for (int i = start; i < start + length; i++) {
			    switch (ch[i]) {
			    case '\\':
			    	help = help.concat("\\\\");
				break;
			    case '"':
			    	help = help.concat("\\\"");
				break;
			    case '\n':
			    	help = help.concat("\\n");
				break;
			    case '\r':
			    	help = help.concat("\\r");
				break;
			    case '\t':
			    	help = help.concat("\\t");
				break;
			    default:
			    	help = help.concat(Character.toString(ch[i]));
				break;
			    }
			}

			if(albumTitleOpen)
				album = help;
			else if(artistNameOpen)
				artist = help;
		}
	}
	
	public void endDocument() throws SAXException {
		artistOpen = false;
		albumOpen = false;
		albumTitleOpen = false;
		artistNameOpen = false;
	}
}
